package com.yonyou.pmclouds.outter.permission;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.iuap.tenant.sdk.RoleAppCenter;
import com.yonyou.iuap.tenant.sdk.UserRoleCenter;
import com.yonyou.pmclouds.basecom.conf.DeployTypeConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class PermissionInfoQuery {
    private ObjectMapper jsonMapper = new ObjectMapper();

    public Set<String> getPermisionIntenant(String userid, String tenantid) {
        // TODO 需要缓存、确认用户如何获取
        Set<String> permissions = new HashSet<>();
        String auth = UserRoleCenter.queryRoleByUser(userid, tenantid, DeployTypeConfiguration.getSysId());
        Map<String, ?> rolemap = null;
        Map<String, ?> promap = null;
        List<String> li = null;
        try {
            if (auth != null) {
                rolemap = jsonMapper.readValue(auth, Map.class);
                li = (List) rolemap.get("data");
                if (li != null) {
                    for (String str : li) {
                        String pro = RoleAppCenter.getAppCode(str, "1");
                        if(StringUtils.isNotEmpty(pro)){
                            promap = jsonMapper.readValue(pro, Map.class);
                            List list = (List) promap.get("data");
                            if(list != null){
                                permissions.addAll(list);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.error("查询功能权限错误");
        }
        return permissions;
    }
}
